package blackstar.plugin.ui;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class StatServlet extends HttpServlet
{
	private final static Log LOGGER = LogFactory.getLog(StatServlet.class);

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		String uri = request.getRequestURI();
		if (!"/".equals(request.getContextPath()))
		{
			uri = uri.substring(request.getContextPath().length());
		}
		LOGGER.info("request:" + uri);
		String[] pathArray = uri.substring(1).split("/");
		if (pathArray.length < 4)
		{
			LOGGER.info("Error Request Path:" + uri);
			response.sendError(404);
		} else if (pathArray.length == 4)
		{
			String jvmid = pathArray[1];
			String date = pathArray[2];
			String type = pathArray[3];
			if ("Simple".equals(type))
			{
				printStatSimple(request, response, jvmid, date);
			} else if ("Detail".equals(type))
			{
				printStatDetail(request, response, jvmid, date);
			} else
			{
				LOGGER.info("Error Stat Type:" + type);
				response.sendError(404);
			}
		} else
		{
			LOGGER.info("Error Request Path:" + uri);
			response.sendError(404);
		}

	}

	private void printStatDetail(HttpServletRequest request,
			HttpServletResponse response, String jvmid, String date)
			throws IOException
	{
		String result = JMXProxyUtils.statDetal(jvmid, date);
		if (result == null)
		{
			result = "jvmid[" + jvmid + "] not found";
		}
		PrintWriter writer = response.getWriter();
		writer.print("{");
		writer.print("result : '");
		writer.print(result);
		writer.print("'}");

	}

	private void printStatSimple(HttpServletRequest request,
			HttpServletResponse response, String jvmid, String date)
			throws IOException
	{
		String result = JMXProxyUtils.statSimple(jvmid, date);
		if (result == null)
		{
			result = "jvmid[" + jvmid + "] not found";
		}

		PrintWriter writer = response.getWriter();
		writer.print("{");
		writer.print("result : '");
		writer.print(result);
		writer.print("'}");
	}

}
